/*
 * @Author: xiaoyan
 * @Date: 2021-11-25 09:28:10
 * @LastEditors: xiaoyan
 * @LastEditTime: 2021-11-25 16:28:51
 * @Description: 上传
 * @FilePath: \user_auth_front\src\components\upload\index.tsx
 */
import { useState } from 'react';
import { Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import { openMinModal } from "@/store/modules/app"
import { useDispatch } from 'redux-react-hook';
function getBase64(file:any) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
export default (props:any)=>{
    const {url} = props;
    const dispatch = useDispatch();
    const [fileList, setFileList] = useState([]);
    const onChange = ({ fileList:newFileList }:any)=>{
        setFileList(newFileList);
    };
    const onPreview = async (file:any)=>{
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        const conf = {
            width:500,
            isCustom:false,
            views:<img alt="预览的图片" style={{ width: '100%' }} src={file.url || file.preview} />,
            title:file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        }
        const action = openMinModal(conf);
        dispatch(action);
    };
    return (
        <ImgCrop rotate>
          <Upload
            action={url}
            listType="picture-card"
            fileList={fileList}
            onChange={onChange}
            onPreview={onPreview}
          >
            {fileList.length < 1 && '上传'}
          </Upload>
        </ImgCrop>
    );
};
